/* typehints:start */
import { Npc } from "../../npcs/npc";
import { People } from "../../people";
import { Goods } from "../../goods/goods";
/* typehints:end */

import { animRemoveElement, getObjectType, makeDiv, waitNextFrame } from "../../../core/utils/utils";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDom } from "../dynamic_dom";
import { SelectBtnGroup } from "../select_btn_group";
import { elementDefine } from "../../defines/element_define";
import { attrDefine } from "../../defines/attr_define";
import { RaceDefine } from "../../defines/race_define";
import { FormElementInput } from "../../../core/utils/modal_dialog_form";

export class HUDGoodsBoard extends BaseHUDPart{
  constructor(root){
    super(root);
  }

  createElements(parent){
    this.element = makeDiv(
			parent,
			"goods_board",
			["remove", 'alert_board'],
			`
      <div class="screen"></div>
      <div class="close-btn"><img src="res/ui/icons/close.svg" /></div>
      <div class="content">
        <div class="btn-group"></div>

        <div class="wrapper">
          <h3 class="name"></h3>

          <div class="page attr-page">
            <p class="message"></p>

            <h4 class="mt-1">物品等级</h4>
            <p class="level"></p>

            <h4 class="mt-1">特性</h4>
            <div class="infos"></div>

            <div class="desc">
              <h4 class="mt-1">功能描述</h4>
              <p></p>
            </div>

            <div class="attrs">
              <h4 class="mt-1">属性</h4>
              <div></div>
            </div>

            <div class="need-attr">
              <h4 class="mt-1">使用要求</h4>
              <div></div>
            </div>
          </div>
          <div class="page inventory-page"></div>
          <div class="page control-page"></div>
        </div>
      </div>
    `
		);
  }
  
  initialize(){
    this.domAttach = new DynamicDom(this.root, this.element);

    /** @type {Goods} */
    this.good = null;

    this.bindCloseBtn();
  }

  createSelectBtnGroup(onlyShowTab = false){
    let btns = [
      {
        text: '属性',
        page: '.wrapper|attr-page',
        active: true
      },
      {
        text: '操作',
        page: '.wrapper|control-page',
      }
    ];
    if(this.good.attr.data.backdropGoods.length > 0){
      btns.splice(1, 0, {
        text: '库存',
        page: '.wrapper|inventory-page',
        click: () => {
          let errors = this.good.getPeopleMatchNeedAttr(this.root.mainPlayer);
          if(errors){
            this.root.gameState.dialogs.showWarning('无法探查', errors.join('<br />'));
            return false;
          }
        }
      })
    }
    if(onlyShowTab){
      btns = btns.filter(item => onlyShowTab.indexOf(item.text) > -1);
    }

    new SelectBtnGroup(this.root, this.element.querySelector('.content'), '.btn-group', btns);
  }

  bindCloseBtn(){
    let screen = this.element.querySelector('.screen');

    this.trackClicks(screen, this.hanldeHideGoodsBoard.bind(this), {
      applyCssClass: ''
    });
  }

  hanldeHideGoodsBoard(){
    this.domAttach.internalDetach(true);
  }

  /**
   * 
   * @param {*} good 
   * @param {*} onlyShowTab 仅显示需要的tab页
   */
  handleShowGoodsBoard(good, onlyShowTab = false){
    /** @type {Goods} */
    this.good = good;
    this.element.querySelector('.name').innerText = good.getTitle();
    this.element.querySelector('.message').innerText = good.getDesc();

    this.createSelectBtnGroup(onlyShowTab);

    this.drawAttrPage(good);
    this.drawControlPage(good);

    if(good.attr.data.backdropGoods.length > 0){
      this.renderInventoryItems();
    }

    this.domAttach.internalAttach();
  }

  renderInventoryItems(){
    let itemsParent = this.element.querySelector('.inventory-page');
    itemsParent.innerHTML = '';

    this.inventory = this.good.attr.data.backdropGoods.map(item => {
      return this.root.worldMap.getGood(item.key, null, {
        num: item.num,
        ...(item.data || {})
      });
    });

    if(this.inventory.length > 0){
      this.inventory.map((item, index) => {
        let num = item.attr.data.num || 1;
        let dom = makeDiv(itemsParent, '', ['item', 'styledButton', item.getLevel()], `
          ${item.getTitle()}
          <span class="num">${num == 1 ? '' : 'x' + num}</span>
        `);
  
        this.trackClicks(dom, () => {
          this.getInventoryItem(item, index, num)
        });
      })
    } else {
      itemsParent.innerHTML = '<p class="text-dark">没有任何物品</p>'
    }
  }

  getInventoryItem(item, index, num){
    let numItem = new FormElementInput({
      id: 'num',
      label: '数量',
      defaultValue: num,
      validator: text => text > 0 && !isNaN(text) && text <= num
    })

    let { ok } = this.root.gameState.dialogs.showForm({
      title: '获取',
      desc: '输入数量获得物品到背包中',
      formElements: [numItem],
    });

    ok.add(() => {
      if(!this.root.backdrop.getGoodAndPut(item.key, {
        ...item.attr.data,
        num: numItem.getValue()
      })) return;

      this.good.attr.data.backdropGoods.map((item, goodIndex) => {
        if(goodIndex == index){
          if(item.num - numItem.getValue() <= 0){
            this.good.attr.data.backdropGoods.splice(goodIndex, 1);
          } else {
            item.num -= numItem.getValue();
          }
        }
      })
      
      if(this.good.peopleLimb || this.good.backpackId){
        this.root.savePlayerData();
      }
      else {
        this.good.saveGoodData();
      }

      this.renderInventoryItems();
    })
  }

  /**
   * 
   * @param {Goods} good 
   */
  drawAttrPage(good){
    let infos = this.element.querySelector('.infos');
    let needAttr = this.element.querySelector('.need-attr');
    let attrs = this.element.querySelector('.attrs');
    let desc = this.element.querySelector('.desc');
    let level = this.element.querySelector('.level')

    level.innerHTML = good.getLevelDesc();
    infos.innerHTML = this.getFeatInfo(good);

    this.drawAttrInfo(attrs, 'div', this.getAttrInfo(good.getAttr()));
    this.drawAttrInfo(needAttr, 'div', this.getAttrInfo(good.getNeedAttr()));
    this.drawAttrInfo(desc, 'p', good.getSpecialInfo());
  }

  drawAttrInfo(dom, v, val){
    let inner = dom.querySelector(v);
    if(val){
      dom.classList.remove('remove');
      inner.innerHTML = val;
    } else {
      dom.classList.add('remove');
    }
  }

  /**
   * 
   * @param {Goods} good 
   * @returns 
   */
  getFeatInfo(good){
    let tags = [];
    let str = '';

    if(good.getIsRace()){
      tags.push(`${RaceDefine[good.getIsRace()].text}使用`)
    }

    let isEquip = good.getIsEquip();
    if(isEquip){
      tags.push(`可装备(${isEquip.map(item => item.text).join('、')})`)
    }

    if (good.getIsLaunch()) {
			tags.push("可发射");
		}

    if (good.getIsDrugs()) {
			tags.push("可食用");
		}

    str = `
      <p>${tags.join('、') || '无特性'}</p>
    `

    return str;
  }

  getAttrInfo(attr){
    let str = '';

    Object.keys(attr).map(key => {
      if(attr[key] !== 0){
        let value = attr[key];

        if(key === 'element'){
          value = value.map(k => elementDefine[k].text).join('、');
        }

        if(key === 'durable'){
          let goodDurable = this.good.attr.data.durable || value;
          value = `${goodDurable}/${value}`;
        }

        str += `
          <p>${attrDefine[key].text}: ${value}</p>
        `
      }
    })

    return str;
  }

  /**
   * 
   * @param {Goods} good 
   */
  drawControlPage(good){
    let controlPage = this.element.querySelector(".control-page");
    controlPage.innerHTML = '';
    
    let controls = good.internalGetControl();

    controls.map(item => {
      let btn = makeDiv(
				controlPage,
				null,
				["styledButton"],
				`
        ${item.text}      
      `
			);

      const controlFn = () => {
        this.hanldeHideGoodsBoard();
        // if(item.close){
        // }
        if(item.sideHustle){
          this.root.mainPlayer.setControl(good, item);
        } else {
          item.fn.call(good);
        }
      }

      this.trackClicks(btn, () => {
        if(item.confirm){
          let { ok } = this.root.gameState.dialogs.showInfo('确认操作', `你是否对<${good.getTitle()}>进行<${item.text}>操作`,
            ['cancel:bad:取消', 'ok:success:确认']
          );

          ok.add(() => {
            controlFn();
          })
        } else {
          controlFn();
        }
      });
    })
  }
}